<?php

namespace app\db\model;

use think\Db;
use think\Exception;
use think\Model;

class DbUsercareRelation extends Model
{

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'create_time';
    protected $updateTime = 'update_time';
    protected $dbName     = 'db_usercare_relation';

    # --------------------------------- 查询类接口 START------------------------------------
    /**
     * 获取医务加入的数据库
     * @param int  $usercare_id 医务ID
     *             $type 数据库类型 0全部1总库2子库             
     * @author MSQ 2021-8-2
    **/
    public function getJoinDatabaseByUsercareId($usercare_id = 0,$type = 0)
    {
        if (!$usercare_id) return false;
        $where = [
            'ur.usercare_id'     => $usercare_id,
            'ur.relation_status' => 1,
            'd.status'           => 1
        ];
        # 查询总库
        if ($type == 1) $where['parent_id'] = 0;
        # 查询子库
        if ($type == 2) $where['parent_id'] = ['GT',0];
        
        $list = db($this->dbName)->alias('ur')
            ->field('d.*')
            ->join('db_database d','d.id=ur.database_id')
            ->where($where)->select();
        if (!$list) return [];
        return $list;
    }
    /**
     * 获取医务加入的指定数据库
     * @param int  $usercare_id 医务ID
     *             $db_ids 要查询的数据库id        
     * @author MSQ 2021-8-2
    **/
    public function getJoinInfoByDbIds($usercare_id = 0,$db_ids = [],$field = '*')
    {
        if (!$usercare_id || !$db_ids) return false;

        $where = [
            'usercare_id'     => $usercare_id,
            'relation_status' => 1,
        ];
        if (is_array($db_ids)) {
            $where['database_id'] = ['IN',$db_ids];
        }else{
            $where['database_id'] = $db_ids;
        }
        if ($field && $field != '*' && count(explode(',', $field)) == 1) {
            // 只取一个字段
            if (is_array($db_ids)) {
                # 有多个数据库取合集
                $list = $this->where($where)->column($field);
            }else{
                $list = $this->where($where)->value($field);
            }
        }else{
            if (is_array($db_ids)) {
                # 有多个数据库取合集
                $list = db($this->dbName)->field($field)->where($where)->select();
            }else{
                $list = db($this->dbName)->field($field)->where($where)->find();
            }
        }
        // if (!$list) return [];
        return $list;
    }
    # ---------------------------------- 查询类接口 END-------------------------------------
   
    
    # ------------------------------- 数据处理类接口 START ----------------------------------
    
    /**
     * 加入数据库
     * @param [type] $addData  添加的数组
     * @author MSQ   2021-8-3
     */
    public function addData($addData = [])
    {
        if (!$addData['database_id'] || !$addData['usercare_id']) return false;
        $res = $this->setAttr('id',null)->isUpdate(false)->save($addData);
        if (!$res) return false;
        return true;
    }
    /**
     * 更新所有加入的数据库权限
     * @param [type] $usercare_id  医务id
     * @author MSQ   2021-8-3
     */
    public function upAllJoinDbAuth($usercare_id = 0)
    {
        if (!$usercare_id) return false;
        $where = [
            'usercare_id' => $usercare_id,
            'relation_status' => 1
        ];
        $databaseAuth = db($this->dbName)->where($where)->column('database_id,relation_auth');
        $authArr = [];
        foreach ($databaseAuth as $k => $v){
            $authArr[$k] = explode(',',$v);
        }
        session('databases_auth',$authArr);
        return true;
    }
    /**
     * 更新指定数据库权限
     * @param [type] $usercare_id  医务id
     * @param [type] $database_id  指定数据库id
     * @author MSQ   2021-8-6
     */
    public function getJoinDbAuth($usercare_id = 0,$database_id = 0)
    {
        if (!$usercare_id || !$database_id) return false;
        # 是否是创建者
        $adminUsercareId  = model('DbDatabase')->getDetails($database_id,'usercare_id');
        $data['is_admin'] = 0;
        $data['database_id'] = $database_id;
        if ($usercare_id == $adminUsercareId) $data['is_admin'] = 1;

        $auths = $this->getJoinInfoByDbIds($usercare_id,$database_id,'relation_auth');

        $data['auth'] = explode(',', $auths);
        # 存入session
        session('database_auth',$data);
        
        return $data;
    }

    /**
     * 加入数据库
     * @param [type] $addData  添加的数组
     * @author MSQ    2021-8-3
     */
    public function saveData($where="",$data=[])
    {
        if (empty($data) || empty($where)) return false;
        Db::startTrans();
        try {
             $this->save($data,$where);
             Db::commit();
             return true;
        }catch(Exception $e){
            Db::rollback();
            return  false;
        }
    }

    # --------------------------------- 数据处理类接口 END ----------------------------------

}
